package controllers

import (
	"encoding/json"
	"strings"
	"weiboxs.com/new_h_glasses/enums"
	"weiboxs.com/new_h_glasses/models"
	"weiboxs.com/new_h_glasses/utils"
)

type LoginController struct {
	BaseController
}

func (c *LoginController) Login() {
	c.Layout = "shared/layout_login.html"
	c.TplName = "login/login.html"
}

func (c *LoginController) DoLogin() {
	username := strings.TrimSpace(c.GetString("UserName"))
	userpwd := strings.TrimSpace(c.GetString("UserPwd"))
	if len(username) == 0 || len(userpwd) == 0 {
		c.jsonResult(enums.JRCodeFailed, "用户名和密码不正确", "")
	}

	userpwd = utils.String2md5(userpwd)
	user, err := models.BackendUserOneByUserName(username, userpwd)
	if user != nil && err == nil {
		if user.Status == enums.Disabled {
			c.jsonResult(enums.JRCodeFailed, "用户被禁用，请联系管理员", "")
		}
		str, _ := json.Marshal(user)
		encrypt, _ := utils.Encrypt(string(str))
		c.Ctx.SetCookie("h_userLogin", encrypt)

		//获取用户信息
		c.jsonResult(enums.JRCodeSucc, "登录成功", "")
	} else {
		c.jsonResult(enums.JRCodeFailed, "用户名或者密码错误", "")
	}
}

func (c *LoginController) Logout() {
	c.DestroySession()
	c.Ctx.SetCookie("h_userLogin", "", -1)
	c.pageLogin()
}
